package demo3;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-07-29
 * Time: 15:47
 */


class MyBlockingDeque{

    private int[] arr;
    private int size;
    private int start;
    private int end;

    public MyBlockingDeque() {
        this.arr = new int[100];
        this.size = 0;
        this.start = 0;
        this.end = 0;
    }

    public void put(int n) throws InterruptedException {
        synchronized (this){
            while (size == arr.length){
                this.wait();
            }
            arr[end] = n;
            size++;
            end++;
            if (end == arr.length){
                end = 0;
            }
            notify();
        }
    }

    public int take() throws InterruptedException {
        synchronized (this){
            while (size == 0){
                this.wait();
            }
            int n = start;
            start++;
            size--;
            if (start == arr.length){
                start = 0;
            }
            notify();
            return arr[n];
        }
    }

}



public class Test {
    public static void main(String[] args) throws InterruptedException {
        //ExecutorService executorService = Executors.newFixedThreadPool(4);
        MyBlockingDeque myBlockingDeque = new MyBlockingDeque();
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    myBlockingDeque.put(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        for (int i = 0; i < 10; i++) {
            System.out.print(myBlockingDeque.take() + " ");
        }
    }
}
